package com.upup.train_management.service.impl;

import com.upup.train_management.entity.Schedule;
import com.upup.train_management.entity.Ticket;
import com.upup.train_management.entity.Train;
import com.upup.train_management.service.BookingService;
import com.upup.train_management.service.ScheduleService;
import com.upup.train_management.service.TicketService;
import com.upup.train_management.repository.ScheduleRepository;
import com.upup.train_management.repository.TrainRepository;
import com.upup.train_management.repository.TicketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class BookingServiceImpl implements BookingService {

    private final TicketService ticketService;
    private final ScheduleService scheduleService;
    private final ScheduleRepository scheduleRepository;
    private final TicketRepository ticketRepository;
    private final TrainRepository trainRepository;

    @Autowired
    public BookingServiceImpl(
            TicketService ticketService,
            ScheduleService scheduleService,
            ScheduleRepository scheduleRepository,
            TicketRepository ticketRepository,
            TrainRepository trainRepository) {
        this.ticketService = ticketService;
        this.scheduleService = scheduleService;
        this.scheduleRepository = scheduleRepository;
        this.ticketRepository = ticketRepository;
        this.trainRepository = trainRepository;
    }

    @Override
    @Transactional
    public Ticket bookTicket(Ticket ticket) {
        // 验证车次是否存在
        Schedule schedule = scheduleRepository.findById(ticket.getScheduleId()).orElse(null);
        if (schedule == null) {
            throw new RuntimeException("车次不存在");
        }

        // 验证车次是否已发车
        if (schedule.getDepartureDateTime().isBefore(LocalDateTime.now())) {
            throw new RuntimeException("该车次已发车，无法预订");
        }

        // 验证车次是否有余票
        if (!checkAvailability(ticket.getScheduleId())) {
            throw new RuntimeException("该车次已无余票");
        }

        // 分配座位 - 使用getSeatClass()方法
        boolean isFirstClass = "一等座".equals(ticket.getSeatClass());
        String seat = assignSeat(ticket.getScheduleId(), isFirstClass);
        ticket.setSeatNumber(seat);

        // 创建票据
        return ticketService.createTicket(ticket);
    }

    @Override
    @Transactional
    public boolean cancelBooking(Long ticketId, Long userId) {
        Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
        if (ticket == null) {
            return false;
        }

        // 验证票是否属于该用户
        if (!ticket.getUserId().equals(userId)) {
            return false;
        }

        // 验证车次是否已发车
        Schedule schedule = scheduleRepository.findById(ticket.getScheduleId()).orElse(null);
        if (schedule == null) {
            return false;
        }

        if (schedule.getDepartureDateTime().isBefore(LocalDateTime.now())) {
            return false;  // 已发车，不能取消
        }

        // 取消票
        return ticketService.cancelTicket(ticketId);
    }

    @Override
    public boolean checkAvailability(Long scheduleId) {
        int availableSeats = scheduleService.getAvailableSeats(scheduleId);
        return availableSeats > 0;
    }

    @Override
    public String assignSeat(Long scheduleId, boolean isFirstClass) {
        // 获取车次信息
        Schedule schedule = scheduleRepository.findById(scheduleId).orElse(null);
        if (schedule == null) {
            throw new RuntimeException("车次不存在");
        }

        // 获取列车信息
        Train train = trainRepository.findById(schedule.getTrainId()).orElse(null);
        if (train == null) {
            throw new RuntimeException("列车信息不存在");
        }

        // 获取已订票信息
        List<Ticket> tickets = ticketRepository.findByScheduleId(scheduleId);

        // 简化的座位分配算法（实际系统中需要更复杂的逻辑）
        int carNumber;
        int seatNumber;
        String seatType = isFirstClass ? "一等座" : "二等座";

        if (isFirstClass) {
            // 一等座
            carNumber = 1 + new Random().nextInt(2); // 假设1-2车厢是一等座
            seatNumber = 1 + new Random().nextInt(60); // 假设每个车厢60个座位
        } else {
            // 二等座
            carNumber = 3 + new Random().nextInt(14); // 假设3-16车厢是二等座
            seatNumber = 1 + new Random().nextInt(80); // 假设每个车厢80个座位
        }

        return String.format("%d车%03d号", carNumber, seatNumber);
    }
}